package com.gujianjian.rabbitmq.consume;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class RabbitmqConsume {

    @Autowired
    private AmqpAdmin amqpAdmin;

    @RabbitListener(queues = "queue.dlx1")
    public void watchListener(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)long tag) throws IOException {
        String queueName = null;
        try {
            String routingKey = message.getMessageProperties().getReceivedRoutingKey();
            byte[] body = message.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            JSONObject jsonObject = objectMapper.readValue(body, JSONObject.class);

            queueName = jsonObject.getStr("queueName");
            log.info("消息routingKey：{}", routingKey);
            log.info("收到消息内容：{}", jsonObject);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            channel.basicAck(tag,false);
            if (queueName != null) {
                amqpAdmin.deleteQueue(queueName);
            }
        }
    }
}
